package edu.ynu.MyProject.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.ynu.MyProject.common.service.LogicService;
import edu.ynu.MyProject.config.EquipmentConfig;
import edu.ynu.MyProject.dao.IEquipmentDAO;
import edu.ynu.MyProject.entity.Equipment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EquipmentService extends LogicService<IEquipmentDAO, Equipment, Long> {
    private final RestTemplate restTemplate;
    private final EquipmentConfig equipmentConfig;
    private TokenService tokenService;

    @Autowired
    public EquipmentService(IEquipmentDAO iEquipmentDAO,
                            EquipmentConfig equipmentConfig,
                            RestTemplate restTemplate,
                            TokenService tokenService) {
        super(iEquipmentDAO);
        this.tokenService = tokenService;
        this.equipmentConfig = equipmentConfig;
        this.restTemplate = restTemplate;
    }

    public ResponseEntity<List<Map<String, Object>>> getDeviceData(Long greenhouseId) {
        System.out.println(greenhouseId);
        List<Long> ids=dao.getDeviceIdsByGreenhouseId(greenhouseId);

        // 构建URL
        String baseUrl = equipmentConfig.getBaseUrl();
        String url =baseUrl+ "?boxNo=" + greenhouseId;

        // 构建body
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("ids", ids);

        // 构建header
        String accessToken = tokenService.getSensorToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);

        // 构建请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        try {
            ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                new ParameterizedTypeReference<List<Map<String, Object>>>() {});
            return response;
        } catch (HttpClientErrorException | HttpServerErrorException ex) {
            // 异常处理
            System.out.println("Error during API request: " + ex.getMessage());
            throw new RuntimeException("API request failed", ex);
        }
    }

    public Map<String,Object> getCameraCapture (Long greenhouseId) {
        String url =equipmentConfig.getCameraCaptureUrl();
        String accessToken = tokenService.getCameraToken();
        int channelNo=equipmentConfig.getChannelNo();
        int quality=equipmentConfig.getQuality();
        String deviceSerial =dao.findSerialByGreenhouseIdAndType(greenhouseId);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 设置请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("accessToken", accessToken);
        body.add("deviceSerial", deviceSerial);
        body.add("channelNo", String.valueOf(channelNo));
        body.add("quality", String.valueOf(quality));
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        try {
            // 发送请求
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    url, HttpMethod.POST, requestEntity,
                    new ParameterizedTypeReference<Map<String, Object>>() {}
            );

            // 返回响应体
            return response.getBody();
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            // 处理 HTTP 错误响应
            System.err.println("HTTP请求错误: " + e.getStatusCode() + " " + e.getResponseBodyAsString());
            throw new RuntimeException("请求失败，服务器返回错误", e);
        } catch (Exception e) {
            // 处理异常
            System.err.println("请求过程中发生异常: " + e.getMessage());
            throw new RuntimeException("请求失败", e);
        }

    }
}
